﻿@{Layout = ""; }

<div ng-controller="AutoRelpyController">
    <div class="panel panel-default">
        <div class="panel-body">
            <input id="fileInput" class="ng-hide" type="file" nv-file-select="" uploader="uploader" />
            <input type="hidden" id="uploadFlag" />
            <tabset>
                <tab heading="首次关注问候语" ng-click="ConcernSelect()">
                    <div ng-show="ConcernReplyResponse.Id>0" class="panel panel-default" style="width:60%;">
                        <div class="panel-body">
                            <fieldset>
                                <div class="form-group">
                                    <label class="col-sm-2 control-label">
                                        回复类型：
                                    </label>
                                    <div class="col-sm-4">
                                        <select name="contenttype" id="contenttypeselect" ng-model="ConcernReplyResponse.ContentType" class="form-control" ng-change="ConcernReplyResponse.ReplyContent='';">
                                            <option value="0">文本</option>
                                            <option value="1">图片</option>
                                            <option value="2">图文素材</option>
                                        </select>
                                    </div>
                                </div>
                            </fieldset>
                            <fieldset>
                                <div class="form-group" ng-show="ConcernReplyResponse.ContentType==1">
                                    <label class="col-sm-2 control-label">回复图片</label>
                                    <div class="col-sm-4">
                                        <div class="imgcrop-preview">
                                            <img src="{{ImgHostUrl+ConcernReplyResponse.ReplyContent}}" style="max-width: 100%; max-height: 100%" onerror="javascript: this.src = '/Content/img/default.png';" />

                                        </div>
                                        <div>
                                            <div style="" class="progress progress-xs" ng-show="uploading">
                                                <div role="progressbar" ng-style="{ 'width': uploader.progress + '%' }" class="progress-bar"></div>
                                            </div>
                                        </div>
                                        <span ng-show="IsCheckedPic" class="text-danger">请选择图片</span>
                                    </div>
                                    <div class="col-sm-6">
                                        <button type="button" class="mb-sm btn btn-info" id="selectconcernImage" ng-click="SelectConcernImage()">
                                            图片选择
                                        </button>
                                        <span class="text-danger">图片大小不得大于128KB，仅支持JPG格式</span>
                                    </div>
                                </div>
                                <div class="form-group" ng-show="ConcernReplyResponse.ContentType==0">
                                    <label class="col-sm-2 control-label">
                                        回复内容：
                                    </label>
                                    <div class="col-lg-8">
                                        <textarea class="form-control" rows="6" maxlength="400" ng-model="ConcernReplyResponse.ReplyContent" ng-bind="ConcernReplyResponse.ReplyContent"></textarea>
                                    </div>
                                </div>
                                <div class="form-group" ng-show="ConcernReplyResponse.ContentType==2">
                                    <label class="col-sm-2 control-label">
                                        图文素材：
                                    </label>
                                    <div class="col-lg-8">
                                        <select class="chosen-single chosen-default" chosen option="ImageTexts" ng-options="option.Title for option in ImageTexts track by option.Id" ng-model="ConcernReplyResponse.ConcernReplySelect">
                                            <option value="">--请选择--</option>
                                        </select>
                                    </div>
                                </div>
                            </fieldset>
                        </div>
                    </div>
                    <button type="button" class="mb-sm btn btn-info" ng-click="SaveConcernReply(ConcernReplyResponse.Id,ConcernReplyResponse.ReplyContent,ConcernReplyResponse.ContentType)">保&nbsp;存</button>
                </tab>
                <tab heading="关键词回复" ng-click="KeyWordSelect()">
                    <button type="button" class="mb-sm btn btn-info" ng-click="AddAutoReply()"><i class="fa fa-plus"></i>新增规则</button>
                    @*<a display="block" href="http://www.zmget.com/article/101.html" style="color: blue; font-size: 16px; width: 100%;margin-top: -20px;margin-left: 20px" target="_blank" class="text-right"> >>>查看自动回复使用教程</a>*@
                    <div ng-show="KeyWordReplyResponse.length>0" ng-repeat="keyword in KeyWordReplyResponse" id="panel{{keyword.Id}}" class="panel panel-default" style="width:83%;">
                        <div ng-class="{'panel-heading-collapsed':panel{{keyword.Id}}}" class="panel-heading">
                            {{KeyWordReplyResponse.length-$index}}.<input type="text" maxlength="10" ng-blur="RoleNameSave($event,keyword.Id,keyword.RoleName)" placeholder="规则名称" ng-value="keyword.RoleName" style="width:170px;box-shadow: 0 0 0 #000 !important; border-radius: 4px; border: 1px solid #dde6e9; background-color: white; font-family: inherit; font-size: 14px; height: 35px; padding: 6px 10px; " />
                            <paneltool tool-collapse="tool-collapse" tool-dismiss="tool-dismiss" ng-init="panelkeyword.Id=true"></paneltool>
                        </div>
                        <div collapse="panel{{keyword.Id}}" class="panel-wrapper">
                            <div class="panel-body">
                                <div class="form-group">
                                    <label class="col-sm-1 control-label">
                                        关键字：
                                        <div class="text-sm text-muted">按Enter</div>
                                    </label>
                                    <div class="col-lg-4">
                                        <input type="text" maxlength="200" tagsinput="tagsinput" ng-value="keyword.KeyWords.join(',')" ng-model="keyword.KeyWords" class="form-control" ng-change="KeyWordSave(keyword.Id,keyword.KeyWords)" />
                                        <span class="help-block">
                                            Values:
                                            <code>{{keyword.KeyWords}}</code>
                                            <input type="hidden" id="originalwords{{keyword.Id}}" value="{{keyword.KeyWords}}" />
                                        </span>
                                    </div>
                                    <label class="col-sm-3 control-label">
                                        @*<span style="text-wrap: none">回复内容：</span>
                                            <span class="text-sm text-muted"  ng-show="keyword.ContentType==0">按Enter</span>
                                            <br />*@
                                        <select name="contenttype" id="contenttypeselect" ng-model="keyword.ContentType" class="form-control" ng-change="keyword.ReplyContent='';">
                                            <option value="0">回复文本</option>
                                            @*<option value="1">图片</option>*@
                                            <option value="2">回复图文素材</option>
                                        </select>


                                    </label>
                                    <div class="col-lg-5" ng-show="keyword.ContentType==0">
                                        <textarea class="form-control" rows="3" maxlength="400" ng-blur="ReplyContentSave($event,keyword.Id,keyword.ReplyContent)" ng-bind="keyword.ReplyContent"></textarea>
                                    </div>
                                    <div class="col-lg-5" ng-show="keyword.ContentType==2">
                                        <select class="chosen-single chosen-default" chosen option="ImageTexts" ng-options="option.Title for option in ImageTexts track by option.Id" ng-model="keyword.ReplySelect" ng-change="ReplyContentSave2(keyword)">
                                            <option value="">--请选择--</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </tab>
                <tab heading="消息自动回复" ng-click="MessageSelect()">
                    <div ng-show="MessageReplyResponse.Id>0" class="panel panel-default" style="width:60%;">
                        <div class="panel-body">
                            <fieldset>
                                <div class="form-group">
                                    <label class="col-sm-2 control-label">
                                        回复类型：
                                    </label>
                                    <div class="col-sm-4">
                                        <select name="contenttype" id="contenttypeselect" ng-model="MessageReplyResponse.ContentType" class="form-control" ng-change="MessageReplyResponse.ReplyContent='';">
                                            <option value="0">文本</option>
                                            <option value="1">图片</option>
                                            <option value="2">图文素材</option>
                                        </select>
                                    </div>
                                </div>
                            </fieldset>
                            <fieldset>
                                <div class="form-group" ng-show="MessageReplyResponse.ContentType==1">
                                    <label class="col-sm-2 control-label">回复图片</label>
                                    <div class="col-sm-4">
                                        <div class="imgcrop-preview">
                                            <img src="{{ImgHostUrl+MessageReplyResponse.ReplyContent}}" style="max-width: 100%; max-height: 100%" onerror="javascript: this.src = '/Content/img/default.png';" />

                                        </div>
                                        <div>
                                            <div style="" class="progress progress-xs" ng-show="uploading">
                                                <div role="progressbar" ng-style="{ 'width': uploader.progress + '%' }" class="progress-bar"></div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-sm-6">
                                        <button type="button" class="mb-sm btn btn-info" id="selectmessageImage" ng-click="SelectMessageImage()">
                                            图片选择
                                        </button>
                                        <span class="text-danger">图片大小不得大于128KB，仅支持JPG格式</span>
                                    </div>
                                </div>
                                <div class="form-group" ng-show="MessageReplyResponse.ContentType==0">
                                    <label class="col-sm-2 control-label">
                                        回复内容：
                                    </label>
                                    <div class="col-lg-8">
                                        <textarea class="form-control" rows="6" maxlength="500" ng-model="MessageReplyResponse.ReplyContent" ng-bind="MessageReplyResponse.ReplyContent"></textarea>
                                    </div>
                                </div>
                                <div class="form-group" ng-show="MessageReplyResponse.ContentType==2">
                                    <label class="col-sm-2 control-label">
                                        图文素材：
                                    </label>
                                    <div class="col-lg-8">
                                        <select class="chosen-single chosen-default" chosen option="ImageTexts" ng-options="option.Title for option in ImageTexts track by option.Id" ng-model="MessageReplyResponse.MessageReplySelect">
                                            <option value="">--请选择--</option>
                                        </select>
                                    </div>
                                </div>
                            </fieldset>
                        </div>
                    </div>
                    <button type="button" class="mb-sm btn btn-info" ng-click="SaveMessageReply(MessageReplyResponse.Id,MessageReplyResponse.ReplyContent,MessageReplyResponse.ContentType)">保&nbsp;存</button>
                </tab>
            </tabset>
        </div>
    </div>
</div>
<script type="text/ng-template" id="passConfirmDialog">
    <div class="ngdialog-message">
        <h3>提示</h3>
        <p>确认将该条数据删除？</p>
        <button type="button" ng-click="confirm()" class="btn btn-primary mr">确认</button>
        <button type="button" ng-click="closeThisDialog('button')" class="btn btn-default">取消</button>
    </div>
</script>
<script>
    App.controller('AutoRelpyController', ["$scope", "$state", "$http", "Notify", "ngDialog", "FileUploader", "$rootScope", "$filter", "$timeout",
    function ($scope, $state, $http, Notify, ngDialog, FileUploader, $rootScope, $filter, $timeout) {
        'use strict';

        $scope.KeyWordSelect = function () {
            $http.get("/WxSet/KeyWordSelect", "").success(function (data) {
                $scope.KeyWordReplyResponse = data;
                angular.forEach($scope.KeyWordReplyResponse, function (value, index) {
                    if (value.ContentType == 2) {
                        value.ReplySelect = $filter('filter')($scope.ImageTexts, { "GroupId": value.ReplyContent })[0];
                    }
                })
            });
        };

        $scope.ConcernSelect = function () {
            $http.get("/WxSet/ConcernSelect", "").success(function (data) {
                $scope.ConcernReplyResponse = data;
                $scope.ConcernReplyResponse.ConcernReplySelect = $filter('filter')($scope.ImageTexts, { "GroupId": $scope.ConcernReplyResponse.ReplyContent })[0];
            });
        };
        $scope.MessageSelect = function () {
            $http.get("/WxSet/MessageSelect", "").success(function (data) {
                $scope.MessageReplyResponse = data;
                $scope.MessageReplyResponse.MessageReplySelect = $filter('filter')($scope.ImageTexts, { "GroupId": $scope.MessageReplyResponse.ReplyContent })[0];
            });
        };

        $http.post("/WxSet/GetAllImageText", {}).success(function (data) {
            $scope.ImageTexts = data;

            $scope.KeyWordSelect();
            $scope.ConcernSelect();
            $scope.MessageSelect();
        });




        // PANEL DISMISS EVENTS
        // -----------------------------------

        // Before remove panel
        $scope.$on('panel-remove', function (event, id, deferred) {

            //console.log('Panel #' + id + ' removing');

            // Here is obligatory to call the resolve() if we pretend to remove the panel finally
            // Not calling resolve() will NOT remove the panel
            // It's up to your app to decide if panel should be removed or not
            ngDialog.openConfirm({
                template: 'passConfirmDialog',
                className: 'ngdialog-theme-default'
            }).then(function (value) {

                deferred.resolve();
                var reg = new RegExp("panel", "g");
                var keywordid = id.replace(reg, "");
                $.ajax({
                    type: "POST",
                    url: "/WxSet/DelKeyWordReply",
                    data: { KeyWordId: keywordid },
                    success: function (data) {

                    }
                });
            }, function (reason) {
            }
            );
        });

        // Panel removed ( only if above was resolved() )
        $scope.$on('panel-removed', function (event, id) {

            //console.log('Panel #' + id + ' removed');
            $scope.KeyWordSelect();

        });

        //$scope.KeyWordSelect = function () {
        //    $http.get("/AutoRelpy/KeyWordReply", "").success(function (data) {
        //        $scope.KeyWordReplyResponse = data;
        //    });
        //};

        //$scope.ConcernSelect = function () {
        //    $http.get("/AutoRelpy/ConcernSelect", "").success(function (data) {
        //        $scope.ConcernReplyResponse = data;
        //    });
        //};



        $scope.KeyWordSave = function (id, keywords) {
            //alert(id);
            if ($("#originalwords" + id).val() != keywords) {
                $.ajax({
                    type: "POST",
                    url: "/WxSet/UpdateKeyWord",
                    data: { KeyWordId: id, KeyWords: keywords },
                    success: function (data) {

                    }
                });
            }
        };

        $scope.ReplyContentSave = function (event, id, replycontent) {
            var obj = $(event.target);
            if (obj.val() != replycontent) {
                $.ajax({
                    type: "POST",
                    url: "/WxSet/UpdateReplyContent",
                    data: { KeyWordId: id, ReplyContent: obj.val() },
                    success: function (data) {
                        Notify.alert('设置成功!', { status: 'success' });
                    }
                });
            }
        }

        $scope.ReplyContentSave2 = function (keyWork) {

            $http.post("/WxSet/UpdateReplyContent",
                    { KeyWordId: keyWork.Id, ReplyContent: keyWork.ReplySelect.GroupId, ContentType: 2 })
                .success(function (data) { Notify.alert('设置成功!', { status: 'success' }); });
        }

        $scope.SaveConcernReply = function (id, replycontent, contenttype) {
            if (contenttype == 2) {
                //replycontent = $scope.ConcernReplyResponse[0].ConcernReplySelect.GroupId;
                replycontent = $scope.MessageReplyResponse.MessageReplySelect.GroupId;
            }
            $.ajax({
                type: "POST",
                url: "/WxSet/UpdateReplyContent",
                data: { KeyWordId: id, ReplyContent: replycontent, ContentType: contenttype },
                success: function (data) {
                    Notify.alert('设置成功!', { status: 'success' });
                }
            });
        }

        $scope.SaveMessageReply = function (id, replycontent, contenttype) {
            debugger;
            if (contenttype == 2) {
                //replycontent = $scope.ConcernReplyResponse[0].ConcernReplySelect.GroupId;
                replycontent = $scope.MessageReplyResponse.MessageReplySelect.GroupId;
            }
            $.ajax({
                type: "POST",
                url: "/WxSet/UpdateReplyContent",
                data: { KeyWordId: id, ReplyContent: replycontent, ContentType: contenttype },
                success: function (data) {
                    Notify.alert('设置成功!', { status: 'success' });
                }
            });
        }

        $scope.AddAutoReply = function () {
            $http.post("/WxSet/AddKeyWordReply", {}).then(function (response) {
                console.log(response);
                $scope.KeyWordReplyResponse = response.data;
            });
        }

        $scope.RoleNameSave = function (event, id, rolename) {
            var obj = $(event.target);
            if (obj.val() != rolename) {
                $.ajax({
                    type: "POST",
                    url: "/WxSet/UpdateRoleName",
                    data: { KeyWordId: id, RoleName: obj.val() },
                    success: function (data) {
                        $scope.KeyWordSelect();
                    }
                });
            }
        }

        //-------------图片选择相关
        //主图
        //$("#selectImage").click(function () {
        //    $("#fileInput").click();
        //    console.log($("#fileInput"));
        //});

        $scope.SelectConcernImage = function () {
            $("#uploadFlag").val(0);
            $("#fileInput").click();
        }
        $scope.SelectMessageImage = function () {
            $("#uploadFlag").val(1);
            $("#fileInput").click();
        }

        var handleFileSelect = function (evt) {
            var file = $scope.uploadSelectFile = evt.currentTarget.files[0];
            var type = '|' + file.type.slice(file.type.lastIndexOf('/') + 1) + '|';
            var size = file.size;
            if (!evt.currentTarget.files[0] || !(('|jpg|jpeg|'.indexOf(type) !== -1) && size < 128000)) {
                Notify.alert('请选择jpg格式文件且大小不大于128KB', { status: 'warning' });
                return false;
            }
            var reader = new FileReader();
            reader.onload = function (evt) {
                $scope.$apply(function ($scope) {
                    if ($("#uploadFlag").val() == "0") {
                        $scope.ConcernReplyResponse.ReplyContent = evt.target.result;
                    } else if ($("#uploadFlag").val() == "1") {
                        $scope.MessageReplyResponse.ReplyContent = evt.target.result;
                    }
                });
            };
            if (file)
                reader.readAsDataURL(file);
        };

        angular.element(document.querySelector('#fileInput')).on('change', handleFileSelect);
        var uploader = $scope.uploader = new FileUploader({
            url: $rootScope.ImgUploadUrl + '?PlatForm=wsd&Path=WxAutoReply'
        });
        uploader.filters.push({
            name: 'imageFilter',
            fn: function (item /*{File|FileLikeObject}*/, options) {
                var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|';

                var size = item.size;
                return ('|jpg|jpeg|'.indexOf(type) !== -1) && size < 1024000;
            },

        });

        // CALLBACKS

        uploader.onWhenAddingFileFailed = function (item /*{File|FileLikeObject}*/, filter, options) {
            //  console.info('onWhenAddingFileFailed', item, filter, options);
        };
        uploader.onAfterAddingFile = function (fileItem) {
            var type = '|' + $scope.uploadSelectFile.type.slice($scope.uploadSelectFile.type.lastIndexOf('/') + 1) + '|';
            var size = $scope.uploadSelectFile.size;
            if ($scope.uploadSelectFile && (('|jpg|jpeg|'.indexOf(type) !== -1) && size < 1024000)) {
                fileItem.upload();
            }
            $scope.uploading = true;

            //    console.info('onAfterAddingFile', fileItem);
        };
        uploader.onAfterAddingAll = function (addedFileItems) {
            //   console.info('onAfterAddingAll', addedFileItems);
        };
        uploader.onBeforeUploadItem = function (item) {
            // console.info('onBeforeUploadItem', item);
        };
        uploader.onProgressItem = function (fileItem, progress) {
            // console.info('onProgressItem', fileItem, progress);
        };
        uploader.onProgressAll = function (progress) {
            //  console.info('onProgressAll', progress);
        };
        uploader.onSuccessItem = function (fileItem, response, status, headers) {

            if ($("#uploadFlag").val() == "0") {
                $scope.ConcernReplyResponse.ReplyContent =  response[0];
            } else if ($("#uploadFlag").val() == "1") {
                $scope.MessageReplyResponse.ReplyContent = response[0];
            }

            $("#fileInput").val("");
            //  console.info('onSuccessItem', fileItem, response, status, headers);
        };
        uploader.onErrorItem = function (fileItem, response, status, headers) {
            //  console.info('onErrorItem', fileItem, response, status, headers);
        };
        uploader.onCancelItem = function (fileItem, response, status, headers) {
            // console.info('onCancelItem', fileItem, response, status, headers);
        };
        uploader.onCompleteItem = function (fileItem, response, status, headers) {
            //  console.info('onCompleteItem', fileItem, response, status, headers);
        };
        uploader.onCompleteAll = function () {
            $scope.uploading = false;
        };

    }]);
</script>
